package huixue.cn.com.rxapp.rx;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import huixue.cn.com.rxapp.R;
import huixue.cn.com.rxapp.base.SimpleActivity;
import huixue.cn.com.rxapp.rx.service.MessengerService;
import huixue.cn.com.rxapp.util.LogUtils;

public class MessagerActivity extends SimpleActivity {


    private static final String TAG = "MainActivity";

    private static final int MSG_SUM = 0x110;

    private Messenger mService;

    private boolean isConn;


    @Override
    public int getLayout() {
        return R.layout.activity_messager;
    }

    @Override
    public void initView() {
        findViewById(R.id.btn1).setOnClickListener(view->{
            Message msgFromClient = Message.obtain(null, MSG_SUM, 5, 6);
            msgFromClient.replyTo = messengerHandler;

            try{
                mService.send(msgFromClient);
            }catch (RemoteException e){
                e.printStackTrace();
            }

        });

        Intent intent = new Intent(this, MessengerService.class);

        bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void addEvent() {

    }


    ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);

            LogUtils.d("MessagerActivity","==onServiceConnected==");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    Messenger messengerHandler = new Messenger(new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            LogUtils.d("MessagerActivity","arg1===>:"+msg.arg1);
        }
    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
    }
}
